/*
 * Copyright 2000-2006 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.gwt.inspections;

import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.*;
import com.intellij.gwt.GwtBundle;
import com.intellij.gwt.GwtConfiguration;
import com.intellij.gwt.i18n.GwtI18nManager;
import com.intellij.gwt.i18n.PropertiesFilesListCellRenderer;
import com.intellij.gwt.i18n.GwtI18nUtil;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.lang.properties.psi.Property;
import com.intellij.lang.properties.psi.PropertiesElementFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.application.Result;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.ide.DataManager;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.text.MessageFormat;

/**
 * @author nik
 */
public class GwtInconsistentLocalizableInterfaceInspection extends LocalInspectionTool {
  private static final Logger LOG = Logger.getInstance("#com.intellij.gwt.inspections.GwtInconsistentLocalizableInterfaceInspection");
  @NonNls private static final String GWT_PROPERTY_KEY_JAVADOC = "/**\n*@gwt.key {0}\n*/";

  @NotNull
  public HighlightDisplayLevel getDefaultLevel() {
    return HighlightDisplayLevel.ERROR;
  }

  public boolean isEnabledByDefault() {
    return true;
  }

  @Nls
  @NotNull
  public String getGroupDisplayName() {
    return GwtInspectionsProvider.GWT_INSPECTIONS_GROUP;
  }

  @Nls
  @NotNull
  public String getDisplayName() {
    return GwtBundle.message("inspection.name.inconsistent.gwt.localizable.interface");
  }

  @NonNls
  @NotNull
  public String getShortName() {
    return "GwtInconsistentI18nInterface";
  }


  @Nullable
  public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    if (!GwtConfiguration.getInstance().isValidConfiguration()) {
      return null;
    }

    if (file instanceof PropertiesFile) {
      PropertiesFile propertiesFile = (PropertiesFile)file;
      return checkPropertiesFile(manager, propertiesFile);
    }

    if (file instanceof PsiJavaFile) {
      final PsiClass[] psiClasses = ((PsiJavaFile)file).getClasses();
      for (PsiClass psiClass : psiClasses) {
        final ProblemDescriptor[] descriptors = checkPsiClass(manager, psiClass);
        if (descriptors != null) {
          return descriptors;
        }
      }
    }
    return null;
  }

  @Nullable
  private static ProblemDescriptor[] checkPsiClass(final InspectionManager manager, final PsiClass psiClass) {
    final GwtI18nManager i18nManager = GwtI18nManager.getInstance(manager.getProject());
    final PropertiesFile[] files = i18nManager.getPropertiesFiles(psiClass);
    if (files.length == 0) {
      return null;
    }

    List<ProblemDescriptor> descriptors = new ArrayList<ProblemDescriptor>();
    for (PsiMethod psiMethod : psiClass.getMethods()) {
      final Property[] properties = i18nManager.getProperties(psiMethod);
      if (properties.length == 0) {
        final String description = GwtBundle.message("problem.description.method.0.doesn.t.have.corresponding.property", psiMethod.getName());
        final LocalQuickFix quickFix = new DefinePropertyQuickfix(i18nManager.getPropertyName(psiMethod), files);
        descriptors.add(manager.createProblemDescriptor(psiMethod, description, quickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
      }
    }
    return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
  }

  private static @Nullable ProblemDescriptor[] checkPropertiesFile(final InspectionManager manager, final PropertiesFile propertiesFile) {
    final GwtI18nManager i18nManager = GwtI18nManager.getInstance(manager.getProject());
    final PsiClass anInterface = i18nManager.getPropertiesInterface(propertiesFile);
    if (anInterface == null) {
        return null;
      }

    List<Property> propertiesWithoutMethods = new ArrayList<Property>();
    final List<Property> properties = propertiesFile.getProperties();
    for (Property property : properties) {
        final PsiMethod method = i18nManager.getMethod(property);
        if (method == null && property.getKey() != null) {
          propertiesWithoutMethods.add(property);
        }
      }

    if (propertiesWithoutMethods.isEmpty()) {
        return null;
      }

    SynchronizeInterfaceQuickFix synchAllQuickfix;
    if (propertiesWithoutMethods.size() > 1) {
        synchAllQuickfix = new SynchronizeInterfaceQuickFix(anInterface, propertiesWithoutMethods);
      }
      else {
        synchAllQuickfix = null;
      }

    List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
    for (Property property : propertiesWithoutMethods) {
        final String key = property.getKey();
        final AddMethodToInterfaceQuickFix quickFix = new AddMethodToInterfaceQuickFix(anInterface, key);
        LocalQuickFix[] fixes = synchAllQuickfix == null ? new LocalQuickFix[]{quickFix} : new LocalQuickFix[]{synchAllQuickfix, quickFix};

      final String description = GwtBundle.message("problem.description.property.0.doesn.t.have.corresponding.method.in.1", key, anInterface.getName());
      problems.add(manager.createProblemDescriptor(property, description, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
    }
    return problems.toArray(new ProblemDescriptor[problems.size()]);
  }

  private static void defineProperty(final PropertiesFile propertiesFile, final String propertyName) {
    final Property property = new WriteCommandAction<Property>(propertiesFile.getProject(), propertiesFile) {
      protected void run(final Result<Property> result) throws Throwable {
        result.setResult(definePropertyImpl(propertiesFile, propertyName));
      }
    }.execute().getResultObject();

    if (property != null) {
      GwtI18nUtil.navigateToProperty(property);
    }
  }

  private static Property definePropertyImpl(final PropertiesFile propertiesFile, final String propertyName) {
    try {
      final PsiElement element = propertiesFile.addProperty(PropertiesElementFactory.createProperty(propertiesFile.getProject(), propertyName, ""));
      return element instanceof Property ? (Property)element : null;
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }

  private static boolean ensureWritable(final PsiElement element) {
    return !ReadonlyStatusHandler.getInstance(element.getProject()).ensureFilesWritable(element.getContainingFile().getVirtualFile()).hasReadonlyFiles();
  }

  private static void addMethod(PsiClass aClass, String propertyName) {
    try {
      final PsiManager psiManager = aClass.getManager();
      String methodName = GwtI18nUtil.convertPropertyName2MethodName(propertyName, psiManager.getNameHelper(), PsiUtil.getLanguageLevel(aClass));

      final PsiClassType javaLangString = PsiType.getJavaLangString(psiManager, aClass.getResolveScope());
      final PsiMethod method = psiManager.getElementFactory().createMethod(methodName, javaLangString);
      method.getModifierList().setModifierProperty(PsiModifier.PUBLIC, false);
      method.getBody().delete();
      final PsiElement addedMethod = aClass.add(method);

      if (!propertyName.equals(methodName)) {
        final String commentText = MessageFormat.format(GWT_PROPERTY_KEY_JAVADOC, propertyName);
        aClass.addBefore(psiManager.getElementFactory().createCommentFromText(commentText, aClass), addedMethod);
      }
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }

  private static class AddMethodToInterfaceQuickFix implements LocalQuickFix {
    private PsiClass myInterface;
    private String myProperty;

    public AddMethodToInterfaceQuickFix(final PsiClass anInterface, final String propertyName) {
      myInterface = anInterface;
      myProperty = propertyName;
    }

    @NotNull
    public String getName() {
      return GwtBundle.message("quickfix.name.create.method.0.in.1", myProperty, myInterface.getName());
    }

    @NotNull
    public String getFamilyName() {
      return GwtInspectionsProvider.GWT_QUICKFIXES_FAMILY;
    }

    public void applyFix(final @NotNull Project project, final ProblemDescriptor descriptor) {
      if (!ensureWritable(myInterface)) {
        return;
      }
      addMethod(myInterface, myProperty);
    }
  }

  private static class SynchronizeInterfaceQuickFix implements LocalQuickFix {
    private PsiClass myInterface;
    private List<Property> myProperties;

    public SynchronizeInterfaceQuickFix(final PsiClass anInterface, final List<Property> properties) {
      myProperties = properties;
      myInterface = anInterface;
    }

    @NotNull
    public String getName() {
      return GwtBundle.message("quickfix.name.synchronize.all.methods.in.0", myInterface.getName());
    }

    @NotNull
    public String getFamilyName() {
      return GwtInspectionsProvider.GWT_QUICKFIXES_FAMILY;
    }

    public void applyFix(final @NotNull Project project, final ProblemDescriptor descriptor) {
      if (!ensureWritable(myInterface)) {
        return;
      }

      for (Property property : myProperties) {
        addMethod(myInterface, property.getKey());
      }
    }
  }

  private static class DefinePropertyQuickfix implements LocalQuickFix {
    private String myPropertyName;
    private PropertiesFile[] myPropertiesFiles;

    public DefinePropertyQuickfix(final String propertyName, final PropertiesFile[] propertiesFiles) {
      myPropertyName = propertyName;
      myPropertiesFiles = propertiesFiles;
    }

    @NotNull
    public String getName() {
      return GwtBundle.message("quickfix.name.create.property.0", myPropertyName);
    }

    @NotNull
    public String getFamilyName() {
      return GwtInspectionsProvider.GWT_QUICKFIXES_FAMILY;
    }

    public void applyFix(@NotNull final Project project, final ProblemDescriptor descriptor) {
      if (myPropertiesFiles.length == 1) {
        final PropertiesFile file = myPropertiesFiles[0];
        if (ensureWritable(file)) {
          final Property property = definePropertyImpl(file, myPropertyName);
          if (property != null) {
            GwtI18nUtil.navigateToProperty(property);
          }
        }
        return;
      }

      final JList list = new JList(myPropertiesFiles);
      final PropertiesFilesListCellRenderer renderer = new PropertiesFilesListCellRenderer();
      list.setCellRenderer(renderer);
      list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      renderer.installSpeedSearch(list);
      new PopupChooserBuilder(list)
        .setTitle(GwtBundle.message("quickfix.popup.title.choose.properties.file"))
        .setItemChoosenCallback(new Runnable() {
          public void run() {
            final int index = list.getSelectedIndex();
            if (index != -1) {
              defineProperty(myPropertiesFiles[index], myPropertyName);
            }
          }
        })
        .createPopup()
        .showInBestPositionFor(DataManager.getInstance().getDataContext());
    }
  }
}
